// import getUrl from './request'
import axios from "axios";
import qs from 'querystring';
import Nprogress from 'nprogress'

// getUrl.then(res => {
//   console.log(res.baseUrl);
// });


const instance = axios.create({timeout: 5000});
// 设置默认请求头
instance.defaults.headers.post['Content-Type'] =
  'application/x-www-form-urlencoded';

instance.defaults.transformRequest = data => qs.stringify(data);


// 请求拦截
instance.interceptors.request.use(
  config => {
    Nprogress.start()
    return config
  },
);

// 响应拦截
instance.interceptors.response.use(response=>{
  Nprogress.done()
  return response.status === 200
      ? Promise.resolve(response)
      : Promise.reject(response)
},error => {
  if (error && error.response) {
    switch (error.response.status) {
      case 400:
        error.message = '错误请求';
        break;
      case 401:
        error.message = '未授权，请重新登录';
        break;
      case 403:
        error.message = '没有访问权限，拒绝访问';
        break;
      case 404:
        error.message = '请求错误,未找到该资源';
        break;
      case 405:
        error.message = '请求方法未允许';
        break;
      case 408:
        error.message = '请求超时';
        break;
      case 500:
        error.message = error.response.data.message;
        break;
      case 501:
        error.message = '网络未实现';
        break;
      case 502:
        error.message = '网络错误';
        break;
      case 503:
        error.message = '服务不可用';
        break;
      case 504:
        error.message = '网络超时';
        break;
      default:
        error.message = `连接错误${error.response.msg}`;
    }
  } else {
    error.message = '连接服务器失败';
  }
  alert(error.message);
  return Promise.reject(error.response);
})   


// 封装的get请求
export function get(url, params, headers) {
  return instance.get(url, {
    params,
    headers,
  });
}

export function post(url, params, headers) {
  return instance.post(url, params, headers);
}
export default instance;